---
--类名: CaptainView.lua
--创建日期: 2018-9-22
--创建人: 宋建邦
--功能描述: 船长室view
--修改内容:

local AvatarFactory = app:getClass("AvatarFactory")
local CaptainBubbleView = import(".CaptainBubbleView")
local NameTitleNode = require("app.world.views.NameTitleNode")
local GRes = Res
local Res = {
     CaptainView = "ui2/room/Scene_room.csb",
     SetNode = "ui2/room/Scene_room_set.csb",
     VisitNode = "ui2/room/Scene_room_visit.csb",
}

local CaptainView = class("CaptainView", app.mvc.ViewBase)
CaptainView.VIEW_ROOT_RES = Res.CaptainView

local base = {}
base.__index = function(obj, k, c) 
    return function(...)
        local arg = {...}
        table.remove(arg, 1)
        local ret 
        if obj and #obj > 0 then
            for i, v in ipairs(obj) do 
                ret = {v[k](v, unpack(arg))}
            end
        end
        return unpack(ret)
    end
end

function CaptainView:init()
    self._setVisible = self.setVisible
    self.setVisible = function(self, b)
        if b == false then
            app:sendMsg("CaptainController", "closeMessageView")
        end
        self:_setVisible(b)
    end
    self:setBackGroundColorType(0)
    self:setNodeEventEnabled(true)

    self:initAnimations()

    self.ctl = app:getInst("CaptainController")
    self:initMap()
    self:initEditTips()
    -- self:addTestBtns()
    self:initButtons()

    self.expbar = app:sendMsg( "PlayerController", "getExpBar" )
    if self.expbar then
        self.expbaroriginstatus = self.expbar:isVisible()
        self.expbar:hide()
    end

    EM:on(app:getInst("CaptainController").RoomDataChange, function()
        self:refresh(app:sendMsg("CaptainController", "getRoomData"))
    end)

    -- EM:on(app:getInst("CaptainController").VisitCountsChange, function(e, v, p)
    --     if self.visitMenu then
    --         self.visitMenu:findChild("Panel/text_1"):setString(string.format(L("captain_praise_count"), tostring(p)))
    --         self.visitMenu:findChild("Panel/text_2"):setString(string.format(L("captain_visit_count"), tostring(v)))
    --     end        
    -- end)

    self.beforeSnapshotHandler = EM:on("photo.openphotoview", function()
        app:sendMsg("PhotoController", "disableButton")
        if self.setMenu then
            self.setMenu:hide()
        end

        if self.visitMenu then
            self.visitMenu:hide()
        end
    end)

    self.afterSnapshotHandler = EM:on("photo.closephotoview", function()
        app:sendMsg("CaptainController", "setFilter", nil)
        if self.editMode then
            self.setMenu:show()
        else
            self.visitMenu:show()
        end
        self:setPlayerNameVisible(true)
    end)

    self.setNameHandler = EM:on("photo.set.showname", function(eventname, arg)
        if arg then
            self:setPlayerNameVisible(true)
        else
            self:setPlayerNameVisible(false)
        end
    end)

    self.setPhotoHandler = EM:on("photo.set.params", function(eventname, arg)
        if not arg then return end

        if arg.type == "face" then
            arg.ret.inter = true
            if arg.data.id == 8 then
                display.pushToast(L("captain_can_not_mount"))
            end

            if arg.data.ani and self.lastHero then
                self.lastHero:playAni({name=arg.data.ani,next="mapidle"})
            end
        elseif arg.type == "filter" then
            if arg.id == 2 then
                app:sendMsg("CaptainController", "setFilter", "GRAY",{0.2, 0.3, 0.5, 0.1})
            else
                app:sendMsg("CaptainController", "setFilter", nil)
            end
        end
    end)

    self.redpointHandler =EM:on(app:getInst("CaptainModelRedPoint").RedPointChange, function()
        -- dump(self)
        self:refreshRedPoint()
    end)
    -- EM:on(app:getInst("CaptainController").MessageListChange, function()
    --     self:refreshMessageList()
    -- end)
end

function CaptainView:setPlayerNameVisible(b)
    if self.lastHero and self.lastHero.nameTitleNode then
        self.lastHero.nameTitleNode:setVisible(b)
    end
end

function CaptainView:refreshRedPoint()
    if checknumber(self.captainID) ~= UD.uid then
        return 
    end

    self.msgStamp = app:sendMsg("CaptainModelRedPoint", "getMessageRedPointStamp")
    self.visStamp = app:sendMsg("CaptainModelRedPoint", "getVisitorRedPointStamp")
    
    local collects = app:sendMsg("CaptainModelRedPoint", "getRedPointCollectors")
    
    if self.visitMenu then
        self.visitMenu:findChild("Panel/Panel_my/btn_1/dot"):setVisible(self.msgStamp > 0 or self.visStamp > 0)
        self.visitMenu:findChild("Panel/Panel_my/btn_2/dot"):setVisible(#collects > 0)
        -- self.visitMenu:findChild("Panel/Panel_my/btn_3/dot"):setVisible(#collects > 0)
    end

    -- for i = 1, 4 do
    --     self:refreshTipsRedPoint(i)
    -- end
    -- self:refreshSetMenuRedPoint()
end

function CaptainView:initAnimations()
    local l = ccui.Layout:create()
    l:setContentSize(cc.size(display.width, display.height))
    l:setBackGroundColor(display.COLOR_BLACK)
    l:setBackGroundColorType(1)
    l:setTouchEnabled(false)
    l:setLocalZOrder(999)
    l:hide()

    self.maskLayer = l
    self:addChild(l)
end

function CaptainView:enterAction()
    self.maskLayer:show()
    self.maskLayer:stopAllActions()
    
    self.maskLayer:runAction(cca.fadeOut(0.8))
end

function CaptainView:quitAction()
    self.maskLayer:show()
    self.maskLayer:stopAllActions()

    local act1 = cca.seq({cca.fadeIn(0.8),cca.callFunc(function()
        app:sendMsg("CaptainController", "closeCaptainView")
        end)})

    self.maskLayer:runAction(act1)
end

function CaptainView:changeAction()
    self.maskLayer:show()
    self.maskLayer:stopAllActions()

    local act1 = cca.seq({cca.fadeIn(0.3),cca.fadeOut(0.8)})
    self.maskLayer:runAction(act1)
end

function CaptainView:onExit()
    EM:removeByName(app:getInst("CaptainController").RoomDataChange)
    -- EM:removeByName(app:getInst("CaptainController").VisitCountsChange)
    EM:remove(self.beforeSnapshotHandler)
    EM:remove(self.afterSnapshotHandler)
    EM:remove(self.setPhotoHandler)
    EM:remove(self.redpointHandler)
    EM:remove(self.setNameHandler)    
    if self.expbar and self.expbaroriginstatus == true then
        self.expbar:show()
    end
    display.purgeUnUsedArmatureCachedData()
    display.removeUnusedSpriteFrames()
    app:sendMsg("CaptainModelRedPoint", "reqClearCollectRedPoint")
    app:sendMsg("CaptainModelRedPoint", "reqClearMessageRedPoint")
    -- local tcinfo = cc.Director:getInstance():getTextureCache():getCachedTextureInfo()
    -- dump(tcinfo, "textureinfo")
end

function CaptainView:initButtons()
    -- self._root:findChild("Panel/")
end

function CaptainView:setCaptainID(uid)
    if self.captainID ~= uid then
        self:resetPlayer()
    end
    self.captainID = uid

    self:showMenuVisit()

    -- app:sendMsg("CaptainController", "reqRoomData", self.captainID)
    -- app:sendMsg("CaptainController", "reqCounts", self.captainID)

    self:clearEnterActionFlag()
end

function CaptainView:highLishtPosition(lid, reset)
    for k, v in pairs(self.collectorMap) do
        local imgCtl = nil

        if math.floor(k/100) == 1 then
            imgCtl = v:findChild("Panel/Image")
        else
            imgCtl = v
        end
        
        if reset then
            imgCtl:setColor(cc.c3b(255, 255, 255))
        else
            if k == lid then
                imgCtl:setColor(cc.c3b(255, 255, 255))
            else
                imgCtl:setColor(cc.c3b(100, 100, 100))
            end
        end
    end
end

function CaptainView:initMap()
    self.id2name = {}
    self.id2name[2] = {
        [211] = "cabinet",
        [221] = "bar",
        [231] = "floor",
        [241] = "wall",
    }
    self.id2name[3] = {
        [311] = "servant",
        [321] = "sofa",
        [331] = "table",
        [341] = "carpet",
        [351] = "picture",
    }
    self.id2name[4] = {
        [411] = "curtain_1",
        [491] = "curtain_2",
        [421] = "light",
        [431] = "weapons",
    }
    self.collectorMap = {}
    --基础
    self.collectorMap[211] = self._root:findChild("Panel/cabinet")
    self.collectorMap[221] = self._root:findChild("Panel/bar")
    self.collectorMap[231] = self._root:findChild("Panel/floor")
    self.collectorMap[241] = self._root:findChild("Panel/wall")

    --高级
    self.collectorMap[311] = self._root:findChild("Panel/servant") -- 仆人
    self.collectorMap[321] = self._root:findChild("Panel/sofa")
    self.collectorMap[331] = self._root:findChild("Panel/table")
    self.collectorMap[341] = self._root:findChild("Panel/carpet")
    self.collectorMap[351] = self._root:findChild("Panel/picture")

    --其它
    self.collectorMap[411] = {self._root:findChild("Panel/curtain_1"), self._root:findChild("Panel/curtain_2")}
    self.collectorMap[421] = self._root:findChild("Panel/light")
    self.collectorMap[431] = self._root:findChild("Panel/weapons")

    setmetatable(self.collectorMap[411], base)

    self:initCollectors()
    self:initText()

    for k, v in pairs(self.collectorMap) do
        if math.floor(k/100) == 1 then
            v:findChild("Panel/Image"):setOpacity(0)
        else
            v:setOpacity(0)
        end
    end
    
    self.barObj = self._root:findChild("Panel/bar_objects_3")
    if self.barObj then
        self.barObj:hide()
    end
end

function CaptainView:initCollectors()
    -- self.collectorMap = {}

    self.id2name[1] = {
        [111] = "objects_4_1",
        [112] = "objects_4_2",
        [113] = "objects_4_3",
        [114] = "objects_4_4",
        [121] = "objects_3_1",
        [122] = "objects_3_2",
        [123] = "objects_3_3",
        [124] = "objects_3_4",
        [131] = "objects_2_1",
        [132] = "objects_2_2",
        [141] = "objects_1_1",
        [142] = "objects_1_2",
    }

    --展品
    self.collectorMap[111] = self._root:findChild("Panel/objects_4_1")
    self.collectorMap[112] = self._root:findChild("Panel/objects_4_2")
    self.collectorMap[113] = self._root:findChild("Panel/objects_4_3")
    self.collectorMap[114] = self._root:findChild("Panel/objects_4_4")
    self.collectorMap[121] = self._root:findChild("Panel/objects_3_1")
    self.collectorMap[122] = self._root:findChild("Panel/objects_3_2")
    self.collectorMap[123] = self._root:findChild("Panel/objects_3_3")
    self.collectorMap[124] = self._root:findChild("Panel/objects_3_4")
    self.collectorMap[131] = self._root:findChild("Panel/objects_2_1")
    self.collectorMap[132] = self._root:findChild("Panel/objects_2_2")
    self.collectorMap[141] = self._root:findChild("Panel/objects_1_1")
    self.collectorMap[142] = self._root:findChild("Panel/objects_1_2")
end

function CaptainView:showTipsString()
    if not self.editMode then
        return
    end

    local arg = {
        type="str", 
        curStr = self.model:getStringConfig().Value,
        curColor = self.model:getStringConfig().Color,
        curBg = self.model:getStringConfig().BoardType,
        curFrame = self.model:getStringConfig().FrameType,
        model = self.model,
        captainView = self,
    }
    app:sendMsg("CaptainController", "showCaptainTips", arg)
end

function CaptainView:showTips(lid, tstr)
    if not self.editMode then
        return
    end

    if self.model == nil then
        return
    end


    self:highLishtPosition(lid)
    local tid = self.model:locationId2Type(lid)
    local collects = app:sendMsg("CaptainController", "getCollectionsByType", tid) --self.model:getMyCollectsByType(tid)
    local curCollectID = checknumber(self.model:getCurrentCollectInLocation(lid))
    table.sort(collects, function(a, b)
        if checknumber(a.ID) == curCollectID then
            return true
        end

        if checknumber(b.ID) == curCollectID then
            return false
        end

        if self.model then
            if (self.model:hasCollect(checknumber(a.ID)) ~= false) ~= (self.model:hasCollect(checknumber(b.ID)) ~= false) then
                return self.model:hasCollect(checknumber(a.ID)) ~= false
            end
        end

        if checknumber(a.quality) == checknumber(b.quality) then
            return checknumber(a.ID) > checknumber(b.ID)
        else
            return checknumber(a.quality) > checknumber(b.quality)
        end
    end)

    local align = {}
    if self.currentCollect then
        local left = self.currentCollect:getParent():convertToWorldSpace(self.currentCollect:getPosition()).x - self.currentCollect:getContentSize().width * 0.5
        local right = display.width - self.currentCollect:getContentSize().width - left

        if left > right then
            align.left = left
        else
            align.right = left + self.currentCollect:getContentSize().width
        end
        if lid == 311 then
            align = {right=614}
        end
    end

    local arg = {
        type=tstr, 
        lid = lid, 
        tid = tid, 
        items = collects,
        curID = curCollectID,
        model = self.model,
        captainView = self,
        lcfg = self.model:locationConfig(lid),
        align = align,
    }

    if arg.lcfg then
        app:sendMsg("CaptainController", "showCaptainTips", arg)
    end
end

function CaptainView:initText()
    self.textFrame = self._root:findChild("Panel/bar_kunang_3")
    self.textLight = self._root:findChild("Panel/bar_light")
    self.textLbl = self._root:findChild("Panel/Text")
    self.collectorMap[531] = self.textLight
    self.collectorMap[631] = self.textLbl
    self.collectorMap[731] = self.textFrame

    self.textLbl:setAnchorPoint(cc.p(0.5, 0.5))
    self.textLbl:setPosition(self.textLight:getPosition())

    self.textLight:addClickEventListener(function(sender)
        print("text clicked!")
    end)
end

function CaptainView:setStringConfig(str, colorID, bgID, frameID)
    self.textLbl:setString(str)
    local lisz = self.textLight:getContentSize()
    local tsz = self.textLbl:getAutoRenderSize()
    if tsz.width > (lisz.width-10) then
        self.textLbl:setScale((lisz.width-10)/tsz.width)
    else
        self.textLbl:setScale(1)
    end
    self.textLbl:setTextColor(self.model:c3bFromCollectID(colorID))
    self:setLocationObj(531, bgID)
    self:setLocationObj(731, frameID)
end

function CaptainView:initEditTips()
    self.tipsPanel = self._root:findChild("Panel_tips")
    self.tipsPanel:show()
    self.tipPanels = {}
    self.tipPanels[1] = self._root:findChild("Panel_tips/Panel_"..tostring(4))
    self.tipPanels[2] = self._root:findChild("Panel_tips/Panel_"..tostring(1))
    self.tipPanels[3] = self._root:findChild("Panel_tips/Panel_"..tostring(3))
    self.tipPanels[4] = self._root:findChild("Panel_tips/Panel_"..tostring(2))
    
    self.tipsRedPoint = {}
    
    for i = 1, 4 do
        self.tipPanels[i]:hide()
        for k, v in pairs(self.id2name[i]) do
            local ctl = self.tipPanels[i]:findChild(v)
            if ctl then
                self.tipsRedPoint[k] = ctl:findChild("Panel/dot")
                ctl = ctl:findChild("Panel")
                ctl:setTouchEnabled(true)
                ctl:addClickEventListener(function(sender)
                    if k == 491 then
                        k = 411
                    end
                    if self.collectorMap[k] then
                        if math.floor(k/100) == 1 then
                            self.currentCollect = self.collectorMap[k]:findChild("Panel")   
                        else
                            self.currentCollect = self.collectorMap[k]    
                        end                        
                    else
                        self.currentCollect = ctl
                    end
                    self:showTips(k, "obj")
                    app:sendMsg("CaptainModelRedPoint", "reqClearCollectRedPointByLocationId", k)
                end)
            end
        end
    end
end

function CaptainView:refreshTipsRedPoint(idx)
    for k, v in pairs(self.id2name[idx]) do
        if self.tipsRedPoint[k] then
            self.tipsRedPoint[k]:setVisible(app:sendMsg("CaptainModelRedPoint", "getLocationsRedPoint", {k}) )
        end
    end
end

function CaptainView:tipsGroupRedPoint(idx)
    local lids = {}
    for k, v in pairs(self.id2name[idx]) do
        table.insert(lids, k)
    end
    return app:sendMsg("CaptainModelRedPoint", "getLocationsRedPoint", lids)
end

function CaptainView:showEditTips(idx)
    for i = 1, 4 do
        if i == idx then
            self.tipPanels[i]:show()
        else
            self.tipPanels[i]:hide()
        end
    end
end

function CaptainView:refreshPlayer(params)
    local heroHolder = self._root:findChild("Panel/player")
    heroHolder:setContentSize(cc.size(0, 0))
    heroHolder:show()

    if self.lastHero then
        return
    end
	
    self:performWithDelay(function()
        params.inBattle = false
        local hero = AvatarFactory.createHero(params)
        hero:setTag(0)
        hero:playAni({name="mapidle",next="mapidle"})
        heroHolder:addChild(hero)

        hero.nameTitleNode = NameTitleNode.new()
        hero.nameTitleNode:setName(params.Name)
        if self.captainID == UD.uid then--自己252, 239, 223
            hero.nameTitleNode:setNameColor(GRes.PlayerNameColors.Self)
        else
            hero.nameTitleNode:setNameColor(GRes.PlayerNameColors.Other)
        end
        if params.GuildName then
            hero.nameTitleNode:setGuildName(params.GuildName)
            local myguildname = app:sendMsg("BiddingController", "myGuildName")
            if myguildname and myguildname == params.GuildName then
                hero.nameTitleNode:setGuildNameColor(GRes.PlayerNameColors.DynastyMy)
            else
                hero.nameTitleNode:setGuildNameColor(GRes.PlayerNameColors.DynastyEnemy)
            end
        end
        if checknumber(params.TitleID) > 0 then
            local titleName, quality = UD:getTitleName(checknumber(params.TitleID))
            hero.nameTitleNode:setTitle(titleName)
            local color
            if quality then
                color = GRes.medal_name_color[quality]
            else
                color = display.COLOR4_WHITE
            end
            if color then
                hero.nameTitleNode:setTitleColor(color)
            end
        end
        hero.nameTitleNode:setScaleX(-1)
        hero.nameTitleNode:setLocalZOrder(100)
        hero:addChild(hero.nameTitleNode)
        hero:addAttachment(hero.nameTitleNode,"point",0,0)
        
        hero:setScaleX(-1)
        self.lastHero = hero

        self:initRoleAction(self.model:getArmatureID())
    end, 0.2)
end

function CaptainView:resetPlayer()
    if self.lastHero then
        self.lastHero:removeFromParent()
        self.lastHero = nil
    end
end

function CaptainView:resetMaid()
    self.lastMaidID = 0
    if self.lastMaid then
        self.lastMaid:removeFromParent()
        self.lastMaid = nil
    end
end

function CaptainView:changeMaid(maidID, collectID)
    if maidID == self.lastMaidID then
        return
    end

    self.lastMaidID = maidID
    
    local maidHolder = self._root:findChild("Panel/servant")
    maidHolder:setContentSize(cc.size(0, 0))
    if self.lastMaid then
        self.lastMaid:removeFromParent()
        self.lastMaid = nil
    end

    self:performWithDelay(function()
        if maidID ~= self.lastMaidID then return end
        local maid = AvatarFactory.createNpcById(maidID)
        maid:setTag(0)
        maid:playAni({name="mapidle",next="mapidle"})
        maidHolder:addChild(maid)
        local cscale = checknumber(GD:getSystemPar("captain_maid_scale"))/100
        if cscale <= 0 then
            cscale = 1
        end
        maid:setScale(cscale)
        maid:setScaleX(-maid:getScaleX())
        self.lastMaid = maid
        self.lastMaidID = maidID
        self.lastMaidHeight = self.lastMaid:getBoundingBox().height

        local ccfg = self.model:collectConifg(collectID)
        if ccfg then
            maid:setPosition(cc.p(maid:getPositionX(), maid:getPositionY() + checknumber(ccfg.npcHeighten)))
            self.lastMaidHeight = self.lastMaidHeight + checknumber(ccfg.npcHeighten)
        end

        self:initRoleAction(collectID)
    end, 0.1)
end

function CaptainView:clearAnimations()
    if self.lastHero then
        self.lastHero:removeFromParent()
        self.lastHero = nil
    end

    if self.lastMaid then
        self.lastMaid:removeFromParent()
        self.lastMaid = nil
    end
end

function CaptainView:refreshCollectors()
end

function CaptainView:changeCollector(lid, cid)
    local lcfg = self.ctl.hLocations[checknumber(lid)]
    if lcfg then
        local t = checknumber(lcfg.type)
        local cs = self.ctl:getCollectionsByType(t)

        -- for()
    end
end

function CaptainView:initSetButtons()
    if not self.setMenu then
        return 
    end

    local btnZhanpin = self.setMenu:findChild("Panel/Panel_btn/btn_1/selected_btn")
    local btnJichu = self.setMenu:findChild("Panel/Panel_btn/btn_2/selected_btn")
    local btnGaoji = self.setMenu:findChild("Panel/Panel_btn/btn_3/selected_btn")
    local btnQita = self.setMenu:findChild("Panel/Panel_btn/btn_4/selected_btn")
    local btnString = self.setMenu:findChild("Panel/Panel_btn/btn_5/selected_btn")
    local btnBack = self.setMenu:findChild("Panel/Panel_btn/btn_6/selected_btn")

    local lastBtn = nil
    local beforeString = nil
    local isStringBtn = false
    local function checkBtn(btn)
        if lastBtn then
            lastBtn:setTouchEnabled(true)
            lastBtn:setBright(true)
        end
        isStringBtn = false
        beforeString = lastBtn

        btn:setTouchEnabled(false)
        btn:setBright(false)
        lastBtn = btn
    end

    btnZhanpin.click = function(sender)
        checkBtn(btnZhanpin)
        self:showEditTips(1)
    end
    btnZhanpin:addClickEventListener(btnZhanpin.click)

    self.checkZhanpin = function()
        btnZhanpin.click()
    end

    btnJichu.click = function(sender)
        checkBtn(btnJichu)
        self:showEditTips(2)
    end
    btnJichu:addClickEventListener(btnJichu.click)

    btnGaoji.click = function(sender)
        checkBtn(btnGaoji)
        self:showEditTips(3)
    end
    btnGaoji:addClickEventListener(btnGaoji.click)

    btnQita.click = function(sender)
        checkBtn(btnQita)
        self:showEditTips(4)
    end
    btnQita:addClickEventListener(btnQita.click)

    self.restoreString = function()
        if isStringBtn then
            beforeString.click()
        end
    end

    btnString:addClickEventListener(function(sender)
        checkBtn(btnString)
        if beforeString ~= btnString then
            isStringBtn = true
        end
        self:showEditTips(0)
        self:showTipsString()
    end)

    btnBack:addClickEventListener(function(sender)
        self:showEditTips(0)
        self:switchToVisitMode()
    end)

    self.setHideBtn = self.setMenu:findChild("Panel/btn_take")

    self:addTouchEvts(self.setHideBtn, self.setMenu)
end

function CaptainView:addTouchEvts(btn, rt)
    local l = ccui.Layout:create()
    l:setContentSize(btn:getContentSize())
    l:setTouchEnabled(true)
    
    btn:addChild(l)
    l:addClickEventListener(function(sender)
        if btn:isTouchEnabled() then
            btn:setTouchEnabled(false)
            btn:setBright(false)
            self:playAni(rt, "out")
        else
            btn:setTouchEnabled(true)
            btn:setBright(true)
            self:playAni(rt, "in")
        end
    end)
end

function CaptainView:playAni(node, aniName)
    local act = node:getTimeline()

    local a = nil

    if act:IsAnimationInfoExists(aniName) then
        a = act:getAnimationInfo(aniName)
	end	
	
	if a then	
        act:gotoFrameAndPlay(a.startIndex, a.endIndex, false)
	end
end

function CaptainView:showMenuSet()
    if not self.setMenu then
        self.setMenu = cc.CSLoader:createNode(Res.SetNode)
        self._root:addChild(self.setMenu)
        self:initSetButtons()
    end

    self.setMenu:show()
    -- self:refreshSetMenuRedPoint()
end

function CaptainView:refreshSetMenuRedPoint()
    if self.setMenu then
        for i = 1, 4 do
            self.setMenu:findChild("Panel/Panel_btn/btn_"..tostring(i).."/dot"):setVisible(self:tipsGroupRedPoint(i))
        end
    end
end

function CaptainView:hideMenuSet()
    if self.setMenu then
        self.setMenu:hide()
    end
end

function CaptainView:switchToEditMode()
    self.editMode = true
    self:showMenuSet()
    self.checkZhanpin()
    self:hideMenuVisit()
end

function CaptainView:switchToVisitMode()
    self.editMode = false
    self:showMenuVisit()
    self:hideMenuSet()
end

function CaptainView:initVisitButtons()
    if not self.visitMenu then
        return
    end

    local btnMySocial = self.visitMenu:findChild("Panel/Panel_my/btn_1/selected_btn")
    local btnMyCollect = self.visitMenu:findChild("Panel/Panel_my/btn_2/selected_btn")
    local btnMyEdit = self.visitMenu:findChild("Panel/Panel_my/btn_3/selected_btn")
    local btnMySnap = self.visitMenu:findChild("Panel/Panel_my/btn_4/selected_btn")
    local btnMyBack = self.visitMenu:findChild("Panel/Panel_my/btn_5/selected_btn")
    local btnMyShare = self.visitMenu:findChild("Panel/Panel_my/btn_6/selected_btn")

    btnMySocial:addClickEventListener(function(sender)
        if self.model then
            app:sendMsg("CaptainController", "openMessageView", self.model)
        end
    end)

    btnMyCollect:addClickEventListener(function(sender)
        if self.model then
            app:sendMsg("CaptainController", "openCollectView", self.model)
        end
    end)

    btnMyEdit:addClickEventListener(function(sender)
        self:switchToEditMode()
    end)

    btnMySnap:addClickEventListener(function(sender)
        self:snapshot()
    end)

    btnMyBack:addClickEventListener(function(sender)
        -- app:sendMsg("CaptainController", "closeCaptainView")
        self:quitAction()
    end)

    btnMyShare:addClickEventListener(function(sender)
        if self.model then
            app:sendMsg("IMRoomController", "shareItem", Enums.TipsType.captainRoom, self.model:getCaptainInfo().Name, self.captainID)
        end
    end)
    
    local btnOtherPraise = self.visitMenu:findChild("Panel/Panel_other/btn_1/selected_btn")
    local btnOtherMessage = self.visitMenu:findChild("Panel/Panel_other/btn_2/selected_btn")
    local btnOtherSocial = self.visitMenu:findChild("Panel/Panel_other/btn_3/selected_btn")
    local btnOtherSnap = self.visitMenu:findChild("Panel/Panel_other/btn_4/selected_btn")
    local btnOtherBack = self.visitMenu:findChild("Panel/Panel_other/btn_5/selected_btn")
    local btnOtherShare = self.visitMenu:findChild("Panel/Panel_other/btn_6/selected_btn")
    
    btnOtherPraise:addClickEventListener(function(sender)
        app:sendMsg("CaptainController", "reqPraise", self.captainID)
        -- app:sendMsg("CaptainController", "leaveMessage", self.captainID, L("captain_praise_message"))
    end)

    btnOtherMessage:addClickEventListener(function(sender)
        if self.model then
            app:sendMsg("CaptainController", "openMessageView", self.model)
        end
    end)

    btnOtherSocial:addClickEventListener(function(sender)
        UIHandler:showHeadMenu(
            {type= Enums.MenuType.visitCaptainRoom, 
            attr=self:userBaseDataFromOwnerInfo(),
            pos=btnOtherSocial:getParent():convertToWorldSpace(cc.p(btnOtherSocial:getPositionX(),btnOtherSocial:getPositionX()))
            })
    end)

    btnOtherSnap:addClickEventListener(function(sender)
        self:snapshot()
    end)

    btnOtherBack:addClickEventListener(function(sender)
        -- app:sendMsg("CaptainController", "closeCaptainView")
        self:quitAction()
    end)

    btnOtherShare:addClickEventListener(function(sender)
        app:sendMsg("IMRoomController", "shareItem", Enums.TipsType.captainRoom, self.model:getCaptainInfo().Name, self.captainID)
    end)

    self.visitHideBtn = self.visitMenu:findChild("Panel/btn_take")
    self:addTouchEvts(self.visitHideBtn, self.visitMenu)
end

function CaptainView:userBaseDataFromOwnerInfo()
    local ownerInfo = self.model:getOwnerInfo()
    local baseInfo = {
        hairID = ownerInfo.HairID,
        faceID = ownerInfo.FaceID,
        hairColorID = ownerInfo.HairColorID,
        raceID = ownerInfo.RaceID,
        classID = ownerInfo.ClassID,
        uid = ownerInfo.Uid,
        name = ownerInfo.Name,
        level = ownerInfo.Lv,
        gender = ownerInfo.Gender,
        hideCaptain = true
    }
    return baseInfo
end

function CaptainView:snapshot()
    app:sendMsg("IMRoomController", "hideView")
    UIHandler:handleMessage({id = Constant.FUNC_TYPE_PHOTOGRAPH,mode = "open"})
end

function CaptainView:showMenuVisit()
    if not self.visitMenu then
        self.visitMenu = cc.CSLoader:createNode(Res.VisitNode)
        self._root:addChild(self.visitMenu)
        self:initVisitButtons()
    end

    self.visitMenu:show()
    local pm = self.visitMenu:findChild("Panel/Panel_my")
    local po = self.visitMenu:findChild("Panel/Panel_other")
    pm:hide()
    po:hide()
    if self.captainID ~= UD.uid then
        po:show()
    else
        pm:show()
    end
end

function CaptainView:hideMenuVisit()
    if self.visitMenu then
        self.visitMenu:hide()
    end
end

function CaptainView:addTestBtns()
    local panel = ccui.Layout:create()

    panel:setBackGroundColorType(1)
    panel:setBackGroundColor(display.COLOR_WHITE)
    panel:setBackGroundColorOpacity(100)
    panel:setContentSize(cc.size(display.width, 50))
    panel:setLayoutType(ccui.LayoutType.HORIZONTAL)

    local function addBtn(tlt, cb)
        local button = ccui.Button:create("button.png", "buttonHighlighted.png")
        button:setTitleFontSize(20)
        button:setScale9Enabled(true)
        button:setContentSize(cc.size(100,50))
        button:setTitleText(tlt)
        -- button:setPosition(display.width*0.9, display.height*0.05)
        button:addClickEventListener(function(sender) 
            if cb then
                cb()
            end
        end)

        local label = display.newTTFLabel({text = tlt, size =24, color = display.COLOR_BLACK}) 
        local size = button:getContentSize()
        label:setPosition(size.width/2, size.height/2)
        button:addChild(label)

        return button
    end

    panel:addChild(addBtn(L("lua_code_text_521"), function() 
        app:sendMsg("CaptainController", "openCollectView", self.model)
    end))
    panel:addChild(addBtn(L("lua_code_text_495"), function() 
        if self.model then
            app:sendMsg("CaptainController", "openMessageView", self.model)
        end
    end))
    panel:addChild(addBtn(L("lua_code_text_519"), function() print("button1") end))
    panel:addChild(addBtn(L("lua_code_text_75"), function() print("button1") end))
    panel:addChild(addBtn(L("lua_code_text_507"), function() print("button1") end))
    panel:addChild(addBtn(L("lua_code_text_166"), function() 
        local capc = app:getInst("CaptainController")
        capc:closeCaptainView()
    end))

    self._root:addChild(panel)
end

function CaptainView:refreshLocations()
    if not self.model then return end

    local ls = self.model:getLocationConfigs()
    local lmap = {}
    for i, v in ipairs(ls) do
        lmap[v.ID] = v.Furniture
    end

    for k, v in pairs(self.collectorMap) do
        self:setLocationObj(k, checknumber(lmap[k]))
    end
end

function CaptainView:setLocationObj(lid, cid)
    lid = checknumber(lid)
    cid = checknumber(cid)
    local k2t = math.floor(lid/100)
    local ctl = self.collectorMap[lid]
    if not ctl then
        return
    end

    if lid == 631 then
        ctl:setOpacity(255)
        return
    end

    if cid > 0 then
        local cfg = self.model:collectConifg(cid)
        if k2t == 1 then
            if cfg then
                local imgctl = ctl:findChild("Panel/Image")
                local imgctl1 = ctl:findChild("Panel/Image_1")
                imgctl:setOpacity(255)
                imgctl:loadTexture(cfg.floder.."/"..cfg.armature..".png")
                if imgctl1 then
                    imgctl1:setOpacity(0)              
    
                    local osz = imgctl:getVirtualRenderer():getOriginalSize()
                    local csz = imgctl:getContentSize()
                    if osz.height ~= csz.height then
                        imgctl1:show()
                        imgctl1:setOpacity(255)
                        imgctl:setOpacity(0)
                        imgctl1:loadTexture(cfg.floder.."/"..cfg.armature..".png")
                    end
                end
            end
        else
            if cfg then
                if lid == 311 then--女仆
                    self:changeMaid(checknumber(cfg.npcId), checknumber(cfg.ID))
                else
                    ctl:setOpacity(255)
                    ctl:loadTexture(cfg.floder.."/"..cfg.armature..".png")
                end
            end
        end
    else
        if k2t == 1 then
            ctl:findChild("Panel/Image"):setOpacity(0)
            if ctl:findChild("Panel/Image_1") then
                ctl:findChild("Panel/Image_1"):setOpacity(0)
            end
        else
            if lid == 311 then--女仆
                self:resetMaid()
            end
            ctl:setOpacity(0)
        end
    end
end

function CaptainView:refreshString()
    local scfg = self.model:getStringConfig()
 
    -- self.textLbl:setString(scfg.Value)

    self:setStringConfig(scfg.Value, checknumber(scfg.Color), checknumber(scfg.BoardType), checknumber(scfg.FrameType))
end

function CaptainView:refresh(m)
    if self.model and self.model:getCaptainID() ~= m:getCaptainID() then
        self:changeAction()
    end
    self.model = m

    self:refreshPlayer(m:getCaptainInfo())
    self:refreshCollectors(m:getOwnedCollectors())
    self:refreshLocations()
    self:refreshString()
    self:refreshVisitCounts()
    self:refreshRedPoint()
    display.purgeUnUsedArmatureCachedData()
    display.removeUnusedSpriteFrames()
end

function CaptainView:refreshVisitCounts()
    if self.visitMenu then
        local p = 0
        local v = 0
        local fp = L("captain_praise_count")
        local fv = L("captain_visit_count")
        if self.captainID ~= UD.uid then
            if self.model then
                p = checknumber(self.model:getServerData().PraisedNum)
                v = checknumber(self.model:getServerData().VisitedNum)
            end
            fp = L("captain_total_praise_count")
            fv = L("captain_total_visit_count")
        else
            if self.model then
                p = checknumber(self.model:getServerData().TodayPraisedNum)
                v = checknumber(self.model:getServerData().TodayVisitedNum)
            end
        end
        self.visitMenu:findChild("Panel/Panel_text/text_1"):setString(string.format(fp, tostring(p)))
        self.visitMenu:findChild("Panel/Panel_text/text_2"):setString(string.format(fv, tostring(v)))
    end  
end

function CaptainView:createTalkBubble()
    local ret = CaptainBubbleView.new()
    ret:hide()

    return ret
end

function CaptainView:getActions(cfg)
    self.actions = self.actions or {}

    if self.actions[checknumber(cfg.ID)] then
        return self.actions[checknumber(cfg.ID)]
    end

    local actcfg = {}
    self.actions[checknumber(cfg.ID)] = actcfg

    local function parseAction(str)
        local ret = {}

        local ps = string.split(str, "|")
        if #ps ~= 3 then
            return nil
        end
        ret.aniName = ps[1]
        ret.talkTxt = ps[2]
        ret.weight = checknumber(ps[3])

        return ret
    end
    local function parseActionArray(str)
        local ret = {totalweight = 0}
        local as = string.split(str, ";")
        for i, v in ipairs(as) do            
            if string.len(v) > 0 then
                local act = parseAction(v)
                if act then
                    ret.totalweight = ret.totalweight + act.weight
                    table.insert(ret, act)
                end
            end
        end
        return ret
    end
    actcfg.idleAction = cfg.idleAction
    actcfg.ownerEnter = {
        acts = parseActionArray(cfg.ownerGoHome),
        cd = 0
    }
    actcfg.guestEnter = {
        acts = parseActionArray(cfg.guestVisit),
        cd = 0
    }

    actcfg.ownerStay = {
        acts = parseActionArray(cfg.ownerStay),
        cd = checknumber(cfg.ownerStayCd)
    }
    actcfg.guestStay = {
        acts = parseActionArray(cfg.guestStay),
        cd = checknumber(cfg.guestStayCd)    
    }

    local function calcRandActions(action)
        if #action.acts > 0 then
            local r = math.random(action.acts.totalweight)
            for i, v in ipairs(action.acts) do
                if r <= v.weight then
                    return v 
                end
                r = r - v.weight
            end
        end
    end

    actcfg.getEnterAction = function()
        local action = actcfg.ownerEnter
        if self.captainID ~= UD.uid then
            action = actcfg.guestEnter
        end

        return calcRandActions(action)
    end

    actcfg.getStayAction = function()
        local action = actcfg.ownerStay
        if self.captainID ~= UD.uid then
            action = actcfg.guestStay
        end

        return calcRandActions(action)
    end

    actcfg.getCD = function()
        local action = actcfg.ownerStay
        if self.captainID ~= UD.uid then
            action = actcfg.guestStay
        end

        return action.cd
    end

    return actcfg
end

function CaptainView:runRoleAction(rnode, bubble, act)
    if not act then
        return
    end

    if bubble and act.talkTxt ~= "0" then
    -- if bubble then
        bubble:setText(L(act.talkTxt))
        bubble:show()
    end
    
    if rnode then
        if rnode.setAction then
            rnode:setAction(act.aniName, false)
        else
            rnode:playAni({name=act.aniName,next="mapidle"})
        end
    end
end

function CaptainView:clearEnterActionFlag()
    self.heroEnterRuned = false
    self.maidEnterRuned = false
end

function CaptainView:initRoleAction(roldid)
    local acfg = app:sendMsg("CaptainController", "getActionConfig", roldid)
    if not acfg then return end
    local actionconfig = self:getActions(acfg)

    self.bubbles = self.bubbles or {}
    if not self.bubbles[roldid] then
        self.bubbles[roldid] = self:createTalkBubble()
    end
    if not self.bubbles[roldid]:getParent() then
        self._root:addChild(self.bubbles[roldid])
    end
    local actnode

    if roldid > 100 then
        local maidHolder = self._root:findChild("Panel/servant")
        self.bubbles[roldid]:setPosition(cc.p(maidHolder:getPositionX(), maidHolder:getPositionY() + self.lastMaidHeight))

        if not self.heroEnterRuned then
            self:runRoleAction(self.lastHero, self.bubbles[roldid], actionconfig.getEnterAction())
            self.heroEnterRuned = true
        end

        actnode = maidHolder
    else
        local heroHolder = self._root:findChild("Panel/player")
        local x,y = self.lastHero:getBonePos("body")
        self.bubbles[roldid]:setPosition(cc.p(heroHolder:getPositionX(), heroHolder:getPositionY() + self.lastHero:getBoundingBox().height))

        if not self.maidEnterRuned then
            self:runRoleAction(self.lastMaid, self.bubbles[roldid], actionconfig.getEnterAction())
            self.maidEnterRuned = true
        end
        actnode = heroHolder
    end
    
    local act = nil
    act = cca.seq({cca.delay(actionconfig.getCD()), cca.callFunc(function()
        if roldid > 100 then
            if self.lastMaid then
                self:runRoleAction(self.lastMaid, self.bubbles[roldid], actionconfig.getStayAction())
            end
        else
            if self.lastHero then
                self:runRoleAction(self.lastHero, self.bubbles[roldid], actionconfig.getStayAction())
            end
        end

        actnode:stopAllActions()
        actnode:runAction(act)
    end)})

    actnode:stopAllActions()
    actnode:runAction(act)
    -- self.bubbles[roldid]:show()
end


return CaptainView